package com.world.cat.service.back;

import com.world.cat.dao.back.HandleLogDao;
import com.world.cat.model.back.Article;
import com.world.cat.model.back.HandleLog;
import com.world.cat.service.sys.BaseService;
import com.world.cat.app.utils.PrivilegeVerifierUtil;
import com.world.common.util.CollectionUtil;
import com.world.common.util.SessionUtil;
import com.world.core.dao.GenericRepository;
import com.world.core.dao.Restrictions;
import com.world.core.dao.SimpleExpression;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import com.world.cat.dao.back.ArticleDao;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class ArticleService extends BaseService<Article> {
    @Resource
    private ArticleDao articleDao;
    @Resource
    private HandleLogDao handleLogDao;

    @Override
    public GenericRepository getDao() {
        return articleDao;
    }

    public Page findPage(Class clazz, String jsonParams, Pageable pageable) throws Exception {
        List<SimpleExpression> expressionList = BaseService.getExpressionByJsonParams(clazz, jsonParams);
        if (!PrivilegeVerifierUtil.verifier(SessionUtil.getUserName(), "/back/article/viewAll")) {
            expressionList.add(Restrictions.eq("creator", SessionUtil.getUserName(), true));
        }
        Page page = getDao().findByPage(expressionList, pageable);
        return page;
    }

    //使用软删除
    public void del(String[] ids, Boolean ifSoft) {
        List<SimpleExpression> expressionList = new ArrayList<>();
        expressionList.add(Restrictions.in("id", CollectionUtil.arrayToSet(ids), true));
        List<Article> os = getDao().findAll(expressionList);
        if (ifSoft) {
            List<HandleLog> handleLogs = new ArrayList<>();
            for (Article o : os) {
                o.setIfDel(1);
                HandleLog handleLog = new HandleLog(o.getId(), o.getTitle(), "删除", "删除文章", "");
                handleLogs.add(handleLog);
//                msgService.saveMsg(SessionUtil.getUserName(), o.getId(), o.getTitle(), "删除", SessionUtil.getUserName() + "删除了您的的文章", o.getCreator());
            }
            articleDao.save(os);
            handleLogDao.save(handleLogs);
        } else {
            articleDao.delete(os);
            List<HandleLog> handleLogs = new ArrayList<>();
            for (Article o : os) {
                HandleLog handleLog = new HandleLog(o.getId(), o.getTitle(), "彻底删除", "彻底删除文章", "");
                handleLogs.add(handleLog);
//                msgService.saveMsg(SessionUtil.getUserName(), o.getId(), o.getTitle(), "彻底删除", SessionUtil.getUserName() + "彻底删除了您的文章", o.getCreator());
            }
            handleLogDao.save(handleLogs);
        }
    }
}
